﻿using System;
using System.Web.Mvc;
using GabageFactory.Models;
using GabageFactory.Utiliy.Crypt;
using System.Text.RegularExpressions;
using System.Net.Mail;
using System.Collections.Generic;

namespace GabageFactory.Controllers
{
    [Authorize]
    public class MessageController : BaseController
    {
        private MessageReposity messageReposity;

        private StackReposity factoryReposity;

        public MessageController()
        {
            messageReposity = new MessageReposity();
            factoryReposity = new StackReposity();
        }
        
        //
        // GET: /User/

        public ActionResult Index(string name, int? factoryId, DateTime? beginTime, DateTime? endTime)
        {
            ActionResult result = AllowForRole(RoleEnum.Administrator);
            if (result != null)
            {
                return result;
            }
            
            int fId = factoryId.HasValue ? factoryId.Value : 0;
            ShowFactoryList(0);

            return View(messageReposity.QueryMessages(fId, beginTime, endTime, name));
        }

        //
        // GET: /User/Details/5

        public ActionResult Details(int id)
        {
            ActionResult result = AllowForRole(RoleEnum.Administrator);
            if (result != null)
            {
                return result;
            }
            return View(messageReposity.GetMessageById(id));
        }

        //
        // GET: /User/Create
        public ActionResult Create()
        {
            ActionResult result = AllowForRole(RoleEnum.Administrator);
            if (result != null)
            {
                return result;
            }
            ShowFactoryList(0);
            ShowPriorityList(0);
            return View(new Message());
        } 

        //
        // POST: /User/Create

        [HttpPost]
        public ActionResult Create(Message message)
        {
            ActionResult result = AllowForRole(RoleEnum.Administrator);
            if (result != null)
            {
                return result;
            }
            try
            {
                validate(message);
                
                messageReposity.CreateMessage(message);
                return RedirectToAction("Index");
            }
            catch
            {
                ShowFactoryList(message.FactoryId);
                ShowPriorityList(message.priority);
                return View(message);
            }
        }
        
        //
        // GET: /Message/Edit/5
        public ActionResult Edit(int id)
        {
            ActionResult result = AllowForRole(RoleEnum.Administrator);
            if (result != null)
            {
                return result;
            }
            Message message = messageReposity.GetMessageById(id);
            ShowFactoryList(message.FactoryId);
            ShowPriorityList(message.priority);
            return View(message);
        }

        //
        // POST: /Message/Edit/5

        [HttpPost]
        public ActionResult Edit(Message message)
        {
            ActionResult result = AllowForRole(RoleEnum.Administrator);
            if (result != null)
            {
                return result;
            }
            try
            {
                validate(message);
                
                Message oldMessage = messageReposity.GetMessageById(message.Id);
                oldMessage.FactoryId = message.FactoryId;
                oldMessage.priority = message.priority;
                oldMessage.beginTime = message.beginTime;
                oldMessage.endTime = message.endTime;
                oldMessage.content = message.content;             
                messageReposity.EditMessage(message);
 
                return RedirectToAction("Index");
            }
            catch
            {
                ShowFactoryList(message.FactoryId);
                ShowPriorityList(message.priority);
                return View(message);
            }
        }
        //
        // GET: /User/Delete/5
        public ActionResult Delete(int id)
        {
            ActionResult result = AllowForRole(RoleEnum.Administrator);
            if (result != null)
            {
                return result;
            }
            Message message = messageReposity.GetMessageById(id);
            messageReposity.DeleteMessage(message);
            return View();
        }

        private void validate(Message message)
        {
            if (message.FactoryId <= 0 || message.FactoryId >= long.MaxValue)
            {
                ModelState.AddModelError("FactoryId", "所属公司不能为空");
            }

            if (message.priority <= 0)
            {
                ModelState.AddModelError("priority", "优先级不能为空");
            }

            if (message.beginTime == null)
            {
                ModelState.AddModelError("beginTime", "开始时间不能为空");
            }

            if (message.endTime == null)
            {
                ModelState.AddModelError("endTime", "结束时间不能为空");
            }
            if (message.endTime <= message.beginTime)
            {
                ModelState.AddModelError("endTime", "结束时间必须大于开始时间");
            }
            
            if (string.IsNullOrEmpty(message.content))
            {
                ModelState.AddModelError("content", "通知内容不能为空");
            }
            else if (message.content.Length > 500)
            {
                ModelState.AddModelError("content", "通知不能超过500个字符");
            }

            if (!ModelState.IsValid)
            {
                throw new Exception("Input form is invalid!");
            }
        }

        protected void ShowPriorityList(long priority)
        {
            List<SelectListItem> priorities = new List<SelectListItem>();
            priorities.Add(new SelectListItem { Text = "高", Value = "3", Selected = (priority == 3) });
            priorities.Add(new SelectListItem { Text = "中", Value = "2", Selected = (priority == 2) });
            priorities.Add(new SelectListItem { Text = "低", Value = "1", Selected = (priority == 1) });

            ViewData["priorities"] = priorities;
        }
    }
}
